package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.alibaba.sdk.android.callback.CallbackContext;
import com.alibaba.sdk.android.login.callback.LoginCallback;
import com.alibaba.sdk.android.session.model.Session;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.been.User;
import com.superfish.cutieshop.dialog.AppLoading;
import com.superfish.cutieshop.http.HttpError;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonLogin;
import com.superfish.cutieshop.utils.AccessTokenKeeper;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.PersistTool;
import com.superfish.cutieshop.utils.ShareUtils;
import com.superfish.cutieshop.utils.SinaUserBean;
import com.superfish.cutieshop.utils.SinaUsersAPI;
import com.superfish.cutieshop.utils.TimeUtils;
import com.superfish.cutieshop.utils.UID;
import com.superfish.cutieshop.utils.UserInfo;
import com.superfish.cutieshop.utils.ValidateUtil;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by lmh on 15/10/10.
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;

    @ViewInject(R.id.et_mobile)
    private EditText et_mobile;
    @ViewInject(R.id.et_password)
    private EditText et_password;
    private PlatformActionListener platformActionListener;
    private AppLoading appLoading;
    private DbUtils db;

    private AuthInfo mAuthInfo;
    /**
     * 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能
     */
    private Oauth2AccessToken mAccessToken;
    /**
     * 注意：SsoHandler 仅当 SDK 支持 SSO 时有效
     */
    private SsoHandler mSsoHandler;
    private AuthListener mAuthListener;
    private SinaUsersAPI mUsersAPI;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar();
        db = DbUtils.create(LoginActivity.this);
        appLoading = new AppLoading(this);
        initWeiboLogin();
        initThirdPartyLogin();
    }

    private void initWeiboLogin() {
        mAuthInfo = new AuthInfo(this, BaseConfig.WEIBO_APPKEY, BaseConfig.WEIBO_REDIRECTURL, BaseConfig.WEIBO_SCOPE);
        mSsoHandler = new SsoHandler(this, mAuthInfo);
        mAuthListener = new AuthListener();
    }

    private void initThirdPartyLogin() {
        platformActionListener = new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                switch (i) {
                    case Platform.ACTION_USER_INFOR:
                        String plat = "";
                        if (platform.getName().equals(QQ.NAME)) {
                            plat = "1";
                        } else if (platform.getName().equals(Wechat.NAME)) {
                            plat = "3";
                        } else {
                            CutieToast.show(LoginActivity.this, getResources().getString(R.string.global_error_accident));
                            return;
                        }
                        PlatformDb db = ShareSDK.getPlatform(platform.getName()).getDb();
                        String emblem = db.getUserId();
                        int gender;
                        if (!TextUtils.isEmpty(db.getUserGender())) {
                            if (db.getUserGender().equals("m")) {
                                gender = 1;
                            } else if (db.getUserGender().equals("f")) {
                                gender = 2;
                            } else {
                                gender = 3;
                            }
                        } else {
                            gender = 3;
                        }
                        String avatar = db.getUserIcon();
                        String nikename = db.getUserName();
                        LogTest.lmh("第三方登录信息：plat=" + plat + ", emblem=" + emblem + ", gender=" + gender + ", avatar=" + avatar + ", nikename=" + nikename);

//                        appLoading.dismiss();
                        fetchThirdPartyLogin(plat, emblem, gender, avatar, nikename);
                        break;
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                appLoading.dismiss();
                CutieToast.show(LoginActivity.this, getResources().getString(R.string.global_error_internet));
            }

            @Override
            public void onCancel(Platform platform, int i) {
                appLoading.dismiss();
            }
        };
    }

    public void initToolBar() {
        mToolbar.setTitle("");
        setAppTitle(R.string.menu_login);
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
    }

    public static void open(Activity act) {
        Intent i = new Intent(act, LoginActivity.class);
        open(act, i);
    }

    @OnClick(R.id.container_delete_mobile)
    public void onClickDeleteMobile(View view) {
        et_mobile.setText("");
    }

    @OnClick(R.id.container_delete_password)
    public void onClickDeletePassword(View view) {
        et_password.setText("");
    }

    @OnClick(R.id.tv_register)
    public void onClickRegister(View view) {
        Register1Activity.open(this);
    }

    @OnClick(R.id.iv_weibo)
    public void onClickWeibo(View view) {
        appLoading.show();
//        ShareUtils.thirdPartyLogin(SinaWeibo.NAME, platformActionListener);
        ShareUtils.weiboLogin(mSsoHandler, mAuthListener);
    }

    @OnClick(R.id.iv_taobao)
    public void onClickTaobao(View view) {
//        appLoading.show();
        ShareUtils.taobaoLogin(this, new LoginCallback() {
            @Override
            public void onSuccess(Session session) {
//                LogTest.lmh("欢迎" + "userid=" + session.getUserId() + ", nick=" + session.getUser().nick + ", islogin=" + session.isLogin() + ", loginTime=" + session.getLoginTime() + ", avatar=" + session.getUser().avatarUrl);
//                CutieToast.show(LoginActivity.this, "登陆成功");
                String emblem = session.getUserId();
                int gender = 3;
                String avatar = session.getUser().avatarUrl;
                String nikename = session.getUser().nick;
                fetchThirdPartyLogin("4", emblem, gender, avatar, nikename);
            }

            @Override
            public void onFailure(int code, String message) {
//                Toast.makeText(MainActivity.this, "授权取消" + code + message,
//                        Toast.LENGTH_SHORT).show();
                LogTest.lmh("淘宝登录失败");
//                CutieToast.show(LoginActivity.this, getResources().getString(R.string.global_error_internet));
            }
        });
    }

    @OnClick(R.id.iv_wechat)
    public void onClickWechat(View view) {
        if (!CommonUtil.isApkExist(this, "com.tencent.mm")) {
            CutieToast.show(this, getResources().getString(R.string.share_nowechatapp));
            return;
        }
        appLoading.show();
        ShareUtils.thirdPartyLogin(Wechat.NAME, platformActionListener);
    }

    @OnClick(R.id.iv_qq)
    public void onClickQQ(View view) {
        appLoading.show();
        ShareUtils.thirdPartyLogin(QQ.NAME, platformActionListener);
    }

    private void fetchThirdPartyLogin(String type, String emblem, int gender, String avatar, String nikename) {
        ZokeParams params = HttpParams.triLogin(mHashCode, type, emblem, gender, avatar, nikename);
        HttpStores.getInstense().login(params);
    }

    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        appLoading.dismiss();
        ResponseInfo result = (ResponseInfo) out.getResult();
        LogTest.lmh("result=" + result.result);
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.tri_login)) {
            String json = (String) result.result;
            GsonLogin gsonLogin = new GsonLogin().fromJson(json);
            if (gsonLogin.info == null || gsonLogin.error_code != 0) {
                //失败
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            if (gsonLogin.info.token == null || gsonLogin.info.user_info == null) {
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            User user = gsonLogin.info.user_info;
            user.isThird = 1;
            UserInfo.getInstense(LoginActivity.this).setUser(user);
            UID.updateToken(LoginActivity.this, gsonLogin.info.token);
            PersistTool.saveBoolean(BaseConfig.ShareKey.ISLOGIN, true);
            this.finish();
            return;
        } else if (url.equals(BaseConfig.UrlBank.mob_login)) {
            String json = (String) result.result;
            GsonLogin gsonLogin = new GsonLogin().fromJson(json);
            if (gsonLogin.error_code == 4002) {
                CutieToast.show(this, getResources().getString(R.string.errorcode_4002));
                return;
            }
            if (gsonLogin.info == null || gsonLogin.error_code != 0) {
                //失败
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            if (gsonLogin.info.token == null || gsonLogin.info.user_info == null) {
                CutieToast.show(this, getResources().getString(R.string.global_error_accident));
                return;
            }
            User user = gsonLogin.info.user_info;
            user.isThird = 0;
            UserInfo.getInstense(LoginActivity.this).setUser(user);
            UID.updateToken(LoginActivity.this, gsonLogin.info.token);
            PersistTool.saveBoolean(BaseConfig.ShareKey.ISLOGIN, true);
            appLoading.dismiss();
            this.finish();
            return;
        }
    }

    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        HttpError error = (HttpError) out.getResult();
        LogTest.lmh("error=" + error.s);
        CutieToast.show(this, getResources().getString(R.string.global_error_internet));
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        CallbackContext.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            String str_mobile = "";
            str_mobile = ValidateUtil.valPhone(et_mobile.getText().toString(), this);
            if (!TextUtils.isEmpty(str_mobile)) {
                et_mobile.setError(str_mobile);
                return true;
            }
            if (TextUtils.isEmpty(et_password.getText().toString())) {
                et_password.setError(getResources().getString(R.string.register_passwordnonull));
                return true;
            }
            appLoading.show();
            fetchMobileLogin(et_mobile.getText().toString(), et_password.getText().toString());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void fetchMobileLogin(String mobile, String pwd) {
        ZokeParams params = HttpParams.mobLogin(mHashCode, mobile, pwd);
        HttpStores.getInstense().login(params);
    }

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what) {
            case BaseConfig.MessageCode.ON_REGISTER_COMPLETE:
                this.finish();
                break;
            default:
                break;
        }
    }

    @OnClick(R.id.tv_forgetpassword)
    public void onClickForgetPassword(View view) {
        ResetPassword1Activity.open(this);
    }

    /**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     * 该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            //从这里获取用户输入的 电话号码信息
            String phoneNum = mAccessToken.getPhoneNum();
            if (mAccessToken.isSessionValid()) {
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(LoginActivity.this, mAccessToken);
                getSinaUserData();
//                CutieToast.show(LoginActivity.this, "微博授权成功");
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = "微博授权失败";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                CutieToast.show(LoginActivity.this, message);
            }
        }

        @Override
        public void onCancel() {
            appLoading.dismiss();
            CutieToast.show(LoginActivity.this, "微博授权取消");
        }

        @Override
        public void onWeiboException(WeiboException e) {
            appLoading.dismiss();
            CutieToast.show(LoginActivity.this, "Auth exception : " + e.getMessage());
        }
    }

    /**
     * 获取新浪微博用户信息
     **/
    private void getSinaUserData() {
        mUsersAPI = new SinaUsersAPI(this, BaseConfig.WEIBO_APPKEY, mAccessToken);
        if (mAccessToken != null && mAccessToken.isSessionValid()) {
            long uid = Long.parseLong(mAccessToken.getUid());
            mUsersAPI.show(uid, new RequestListener() {
                @Override
                public void onWeiboException(WeiboException e) {
                    appLoading.dismiss();
                    CutieToast.show(LoginActivity.this, e.getMessage());
                }

                /**
                 * 用户信息获取成功
                 */
                @Override
                public void onComplete(String response) {
                    if (!TextUtils.isEmpty(response)) {
                        SinaUserBean user = SinaUserBean.parse(response);
                        if (user != null) {
                            LogTest.lmh("userImage_" + user.avatar_hd
                                    + " userName_" + user.screen_name
                                    + "  userId" + user.idstr);
//                            fetchSinaLogin(user.idstr, user.screen_name,
//                                    user.avatar_hd);
                            int gender;
                            if (user.gender.equals("m")) {
                                gender = 1;
                            } else if (user.gender.equals("f")) {
                                gender = 2;
                            } else {
                                gender = 3;
                            }
                            fetchThirdPartyLogin("2", user.idstr, gender, user.avatar_hd, user.screen_name);
                        } else {
                            appLoading.dismiss();
                            CutieToast.show(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.global_error_accident));
                        }
                    }
                }
            });
        }
    }


}


